<template>
  <div class="users">
    <div id="hehe" v-if="isShow"></div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="query"
            @change="onSearch"
            clearable
          >
            <template #append>
              <el-button
                icon="el-icon-search"
                @keyup.enter="onSearch"
              ></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button type="primary" @click="goAddUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table border style="width: 100%;" :data="users">
        <el-table-column type="index" label="#" width="50"> </el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template #default="{ row }">
            <el-switch
              v-model="row.mg_state"
              @change="onChangeOfUserState(row.id, $event)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row:user }">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="goEditUser(user)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="user.username === 'admin'"
              @click="delUser(user)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="goAllocRole(user)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 当每页条数改变时触发：@size-change -->
      <!-- 当前页码改变时触发：@current-change -->
      <!-- 当前页码：current-page -->
      <!-- 每页显示条数的可选项：page-sizes -->
      <!-- 当前的每页显示条数：page-size -->
      <!-- 控制显示哪些布局内容：layout -->
      <!-- 总条数：total -->
      <el-pagination
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        :current-page="page.current"
        :page-sizes="[1, 2, 5, 10, 15, 20, 50, 100]"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialog.visible"
      width="50%"
    >
      <template #default>
        <el-form
          ref="addUserForm"
          label-width="70px"
          :model="addUserDialog.form.data"
          :rules="addUserDialog.form.rules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model.trim="addUserDialog.form.data.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model.trim="addUserDialog.form.data.password"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.trim="addUserDialog.form.data.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model.trim="addUserDialog.form.data.mobile"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="addUserDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialog.visible"
      width="50%"
    >
      <template #default>
        <el-form
          ref="editUserForm"
          label-width="70px"
          :model="editUserDialog.form.data"
          :rules="editUserDialog.form.rules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model.trim="editUserDialog.form.data.username"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.trim="editUserDialog.form.data.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model.trim="editUserDialog.form.data.mobile"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="editUserDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="allocRoleDialog.visible"
      width="50%"
      @closed="allocRoleDialog.newRoleId = ''"
    >
      <template #default>
        <div class="mb-10px">
          当前的用户：{{ allocRoleDialog.user.username }}
        </div>
        <div class="mb-10px">
          当前的角色：{{ allocRoleDialog.user.role_name }}
        </div>
        <div>
          分配新角色：
          <el-select v-model="allocRoleDialog.newRoleId">
            <el-option
              v-for="v in allocRoleDialog.roleList"
              :key="v.id"
              :label="v.roleName"
              :value="v.id"
            ></el-option>
          </el-select>
        </div>
      </template>
      <template #footer>
        <el-button @click="allocRoleDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="allocRole">确 定</el-button>
      </template>
    </el-dialog>
    <sync-test :title.sync="syncTestTitle"></sync-test>
  </div>
</template>

<script>
import SyncTest from '../components/SyncTest.vue';

export default {
  name: 'users',
  components: { SyncTest },
  data() {
    return {
      allocRoleDialog: {
        visible: false,
        roleList: null,
        // 保存当前操作的用户信息
        user: null,
        // 保存选中的角色id
        newRoleId: '',
      },
      // 添加的验证
      addUserDialog: {
        visible: false,
        form: {
          data: {
            username: '',
            password: '',
            email: '',
            mobile: '',
          },
          rules: {
            username: [
              { required: true, message: '请输入用户名', trigger: 'change' },
              {
                min: 2,
                max: 16,
                message: '用户名长度在2~16个字符之间',
                trigger: 'change',
              },
            ],
            password: [
              { required: true, message: '请输入密码', trigger: 'change' },
              {
                min: 6,
                max: 16,
                message: '密码长度在6~16个字符之间',
                trigger: 'change',
              },
            ],
            email: [
              {
                pattern: /^\w+(\.\w+)*@\w+(\.\w{2,})+$/,
                message: '邮箱格式不正确',
                trigger: 'change',
              },
            ],
            mobile: [
              {
                pattern: /^1[356789]\d{9}$/,
                message: '手机号码格式不正确',
                trigger: 'change',
              },
            ],
          },
        },
      },
      // 编辑的验证
      editUserDialog: {
        visible: false,
        form: {
          data: {
            id: '',
            username: '',
            email: '',
            mobile: '',
          },
          rules: {
            email: [
              {
                pattern: /^\w+(\.\w+)*@\w+(\.\w{2,})+$/,
                message: '邮箱格式不正确',
                trigger: 'change',
              },
            ],
            mobile: [
              {
                pattern: /^1[356789]\d{9}$/,
                message: '手机号码格式不正确',
                trigger: 'change',
              },
            ],
          },
        },
      },

      isShow: false,
      query: '',
      page: {
        total: 0,
        size: 10,
        current: 1,
      },
      users: [],
    };
  },
  methods: {
    // 分配角色
    async allocRole() {
      const { newRoleId, user, roleList } = this.allocRoleDialog;
      if (!newRoleId) {
        return this.$message.warning('请选择新角色');
      }
      const { data: res } = await this.__apis.user.allocRole(
        user.id,
        newRoleId
      );
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success('角色分配成功');
      // 根据选中的角色id，去角色列表中找出这个id对应的角色对象，然后把这个对象的角色名称直接赋值给操作的这个用户的角色名称即可，不用再去获取用户列表
      user.role_name = roleList.find((v) => v.id === newRoleId).roleName;
      this.allocRoleDialog.visible = false;
    },
    // 显示分配角色对话框
    async goAllocRole(user) {
      if (!this.allocRoleDialog.roleList) {
        const { data: res } = await this.__apis.role.list();
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        this.allocRoleDialog.roleList = res.data;
      }
      this.allocRoleDialog.user = user;
      this.allocRoleDialog.visible = true;
    },
    // 编辑用户
    editUser() {
      this.$refs.editUserForm.validate().then(() => {
        this.__apis.user.edit(this.editUserDialog.form.data).then((res) => {
          if (res.data.meta.status === 200) {
            this.$message.success('更新用户成功');
            this.editUserDialog.visible = false;
            this.getUsers();
          } else {
            this.$message.error(res.data.meta.msg);
          }
        });
      });
    },
    goEditUser(user) {
      this.editUserDialog.visible = true;

      this.editUserDialog.form.data = this._.pick(user, [
        'id',
        'username',
        'email',
        'mobile',
      ]);
    },
    delUser(user) {
      this.$confirm(`此操作将永久删除「${user.username}」, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.__apis.user.del(user.id).then((res) => {
            if (res.data.meta.status === 200) {
              this.$message.success('删除成功');
              this.getUsers();
            } else {
              this.$message.error(res.data.meta.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    addUser() {
      this.$refs.addUserForm
        .validate()
        .then(() => {
          return this.__apis.user.add(this.addUserDialog.form.data);
        })
        .then((res) => {
          if (res.data.meta.status === 201) {
            this.$message.success('用户添加成功');
            this.addUserDialog.visible = false;
            this.$refs.addUserForm.resetFields();
            this.getUsers();
          } else {
            this.$message.error(res.data.meta.msg);
          }
        });
    },
    goAddUser() {
      this.addUserDialog.visible = true;
    },
    // 修改用户状态
    onChangeOfUserState(uid, state) {
      this.__apis.user.changeState(uid, state).then((res) => {
        if (res.data.meta.status === 200) {
          this.$message.success('状态修改成功');
        } else {
          this.$message.error(res.data.meta.msg);
        }
      });
    },
    onSearch() {
      this.page.current = 1;
      this.getUsers();
    },
    onCurrentChange(current) {
      this.page.current = current;
      this.getUsers();
    },
    onSizeChange(size) {
      this.page.size = size;
      this.getUsers();
    },
    getUsers() {
      this.__apis.user
        .list({
          query: this.query,
          pagenum: this.page.current,
          pagesize: this.page.size,
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.page.total = res.data.data.total;
            this.users = res.data.data.users;
          } else {
            this.$message.error(res.data.meta.msg);
          }
        });
    },
  },
  created() {
    this.getUsers();
  },
  mounted() {
    this.isShow = true;
    console.log(document.querySelector('#hehe'), 'hehe1');
    // 将回调延迟到下次 DOM 更新循环之后执行.
    this.$nextTick(() => {
      console.log(document.querySelector('#hehe'), 'hehe2');
    });
  },
};
</script>

<style lang="less" scoped>
.users {
  .el-card {
    margin-top: 20px;
    .el-table {
      margin-top: 20px;
    }
    .el-pagination {
      margin-top: 20px;
    }
  }
  .mb-10px {
    margin-bottom: 10px;
  }
}
</style>
